<template>
  <div v-if="!typerInitialized">
    <tg-form-basic
      ref="ref-main"
      :title="title"
      :max-height="maxHeight"
      :hold-height="holdHeight"
      :form="form"
      :control-bar="controlBar"
    />
    <component
      :is="item.component"
      v-for="(item, index) in components"
      :key="buildDOMKey(item, index)"
      :ref="`ref-sub-${index}`"
      v-bind="item.props"
      v-on="item.events"
    />
  </div>
</template>

<script lang="ts">
/*
prop 列表 [参考 Template]
  operate: 'edit' | 'view' 操作类型
  params: any 参数
  dynamicModel: any 动态模型
metaType 列表 [参考 TgFormBasic]
  title
  maxHeight
  holdHeight
  form
  controlBar
ref 列表
  ref-main [默认]
  ref-sub-${index}
*/
import { Component, Prop } from 'vue-property-decorator'
import { ITgFormBasic } from '@TG/interface/types/component'
import { isEmpty } from '@TG/kit/validate'
import Template from './Template'
import TgFormBasic from '@TG/components/TgForm/TgFormBasic.vue'

@Component({
  name: 'TyperFormBasic',
  components: {
    TgFormBasic
  }
})
export default class extends Template {
  @Prop({ type: String, required: true }) protected operate!: 'edit' | 'view'
  @Prop({ type: Object, default: {} }) protected params!: any
  @Prop({ type: Object, default: {} }) protected dynamicModel!: any

  get title() {
    return this.getMeta(this, 'title')
  }

  get maxHeight() {
    return this.getMeta(this, 'maxHeight')
  }

  get holdHeight() {
    return this.getMeta(this, 'holdHeight')
  }

  get form() {
    return this.getMeta(this, 'form')
  }

  get controlBar() {
    let showSave: boolean = true
    let showReset: boolean = true
    if (this.operate === 'view') {
      showSave = false
      showReset = false
    }
    return Object.assign({}, this.getMeta(this, 'controlBar'), {
      showSave,
      showReset
    })
  }

  public initTemplate() {
    super.initTemplate()
    let params = this.params
    if (isEmpty(params)) {
      params = this.$route.query && this.$route.query.params
    }
    if (isEmpty(params)) {
      params = this.$route.params && this.$route.params.params
    }
    let dynamicModel = this.dynamicModel
    if (isEmpty(dynamicModel)) {
      dynamicModel = this.$route.query && this.$route.query.dynamicModel
    }
    if (isEmpty(dynamicModel)) {
      dynamicModel = this.$route.params && this.$route.params.dynamicModel
    }
    let operate: 'add' | 'edit' | 'view' = this.operate
    if (operate === 'edit' && isEmpty(params)) {
      operate = 'add'
    }
    const form = this.ref() as ITgFormBasic
    form.initForm(operate, params, dynamicModel)
  }

  public getTemplateName() {
    return 'TyperFormBasic'
  }

  public getMainData() {
    const form = this.ref() as ITgFormBasic
    return form.getModel()
  }

  public refresh() {
    // 空实现
  }

  public defaultRef() {
    return 'ref-main'
  }
}
</script>
